/**
 * 
 */
package se.chalmers.spexet.booking.server;
import se.chalmers.spexet.booking.common.*;
import java.util.concurrent.*;
import se.chalmers.spexet.booking.model.*;
import java.util.*;
import java.util.concurrent.atomic.*;
/**
 * @author Winquman
 *
 */
public class ServerModel {
	private final Version version;
	private ConcurrentSkipListSet<SalesPeriod> periods;
	private AtomicInteger nextOrderID, nextSalesPeriodID;
	
	public ServerModel(Version v) {
		nextOrderID = new AtomicInteger(0);
		nextSalesPeriodID = new AtomicInteger(0);
		periods = new ConcurrentSkipListSet<SalesPeriod>();
		version = v;
	}
	
	public void initEmptyModel() {
		periods.add(new SalesPeriod(nextSalesPeriodID.getAndIncrement(), GregorianCalendar.getInstance()));
	}
	
	public synchronized void finalizeSalesPeriod(User finalizedBy) throws IllegalStateException {
		SalesPeriod sp = periods.last();
		try {
			sp.finalize(finalizedBy);
		} catch (InvalidOrderModificationException e) {
			IllegalStateException f = new IllegalStateException("Program is in an illegal state, aborting!");
			f.initCause(e);
			throw f;
		}
	}
}
